package com.mzhmxh.control;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mzhmxh.pojo.SmbmsProvider;
import com.mzhmxh.service.ProviderService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

/**
 * @Author LiJinCheng
 * @Date 2020/7/11 6:17 下午
 * @Version 1.0
 * @package com.mzhmxh.control
 **/
@Controller
@RequestMapping("/provider")
public class ProviderControl {
    @Autowired
    private ProviderService providerService;

    @RequestMapping("/getList")
    @ResponseBody
    public String getList(JsonMapper mapper) {
        try {
            List<SmbmsProvider> list = providerService.getList();
            return mapper.writeValueAsString(list);
        } catch (Exception e) {
            return null;
        }
    }


    @RequestMapping("/add.html")
    public String add() {
        return "provider/add";
    }

    @RequestMapping("/list.html")
    @ResponseBody
    public String list(JsonMapper mapper, Integer curr, SmbmsProvider provider, String proCode, String proName) {
        try {
            if (curr == null) {
                curr = 1;
            }
            if (proCode != null) {
                provider.setProcode(proCode);
            }
            if (proName != null) {
                provider.setProname(proName);
            }
            PageHelper.startPage(curr, 5);
            List<Map<String, Object>> list = providerService.getListByKey(provider);
            return mapper.writeValueAsString(list);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/page.html")
    @ResponseBody
    public String page(JsonMapper mapper, Integer curr, SmbmsProvider provider, String proCode, String proName) {
        try {
            if (curr == null) {
                curr = 1;
            }
            if (proCode != null) {
                provider.setProcode(proCode);
            }
            if (proName != null) {
                provider.setProname(proName);
            }
            PageHelper.startPage(curr, 5);
            List<Map<String, Object>> list = providerService.getListByKey(provider);
            PageInfo pageInfo = new PageInfo(list);
            System.out.println(pageInfo);
            Map<String, Object> map = new HashMap<>();
            map.put("pagess", pageInfo.getPages());
            map.put("pageNum", pageInfo.getPageNum());
            map.put("totals", pageInfo.getTotal());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/list")
    public String list() {
        return "provider/list";
    }

    @RequestMapping("/view.html")
    public String view(Integer proid, Model model) {
        SmbmsProvider smbmsProvider = providerService.selectByPrimaryKey(Long.valueOf(proid));
        model.addAttribute("pro", smbmsProvider);
        return "provider/view";
    }

    @RequestMapping("/delete.html")
    public String delete(Integer proid, Model model) {
        int i = providerService.deleteByPrimaryKey(Long.valueOf(proid));
        if (i == 1) {
            return "provider/liset.html";
        }
        return "provider/liset.html";
    }


    @RequestMapping(value = "/addsave", method = RequestMethod.POST)
    public String addProviderSave(SmbmsProvider provider, HttpSession session, HttpServletRequest request,
                                  @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                int filesize = 500000;
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + new Random().nextInt(1000000) + "_Personal.jpg";
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPicPath = path + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePicPath = path + File.separator + fileName;
                    }


                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            provider.setCreationdate(new Date());

            try {
                if (providerService.add(provider)) {
                    return "redirect:/provider/list";
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return "provider/add";
    }

    @RequestMapping("/modify.html")
    public String modify(Model model, Integer proid) {
        SmbmsProvider smbmsProvider = providerService.selectByPrimaryKey(Long.valueOf(proid));
        model.addAttribute("provider", smbmsProvider);
        return "provider/modify";
    }

}
